package com.hnblc.blcwms.rest.exceptionhandler;

import com.hnblc.blcwms.common.exceptions.ErrorDescription;
import com.hnblc.blcwms.common.exceptions.GeneralException;
import com.hnblc.blcwms.common.exceptions.ManualValidationFailException;
import com.hnblc.blcwms.common.interaction.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice
public class WebExceptionHanlder {

    private static final Logger logger = LoggerFactory.getLogger(WebExceptionHanlder.class);

    /**
     * 处理验证失败异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public RestResponse handleBindException(MethodArgumentNotValidException ex) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        StringBuffer msgBuffer = new StringBuffer();
        fieldErrors.forEach(item ->{
            msgBuffer.append("[").append(item.getField())
            .append("]")
            .append(item.getDefaultMessage()).append("；");
        });
        return new RestResponse(new GeneralException(ErrorDescription.ERROR_REQUEST_VALIDATION_FAIL_0,msgBuffer.toString()));//返回错误信息
    }

    @ExceptionHandler(ManualValidationFailException.class)
    @ResponseStatus(HttpStatus.OK)
    public RestResponse handleValidationException(ManualValidationFailException ex) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
//        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        return new RestResponse(new GeneralException(ErrorDescription.ERROR_REQUEST_VALIDATION_FAIL_0,ex.getMessage()));//返回错误信息
    }
    /**
     * 处理自定义全局异常
     * @param ex
     * @return
    */
    @ExceptionHandler(GeneralException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestResponse handleCustomException(GeneralException ex) {
        RestResponse result = new RestResponse(ex);
        logger.error("custom exception occurred :error code:"+ex.getCode()+",error detail: "+ex.getLocalizedMessage()+"："+ex.toString(),ex);
        ex.printStackTrace();
        return result;
    }

    /**
     * 处理未知未捕获系统异常
     * @param systemEx
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public RestResponse badRequestException(Exception systemEx) {
        RestResponse result = new RestResponse(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,systemEx.getMessage()));
        logger.error("wrong format of parameter,detail:"+systemEx.getMessage()+"："+systemEx.toString(),systemEx);
        systemEx.printStackTrace();
        return result;
    }

    /**
     * 处理未知未捕获系统异常
     * @param systemEx
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestResponse handleUnknownException(Exception systemEx) {
        RestResponse result = new RestResponse(new GeneralException(ErrorDescription.ERROR_OTHER_1,systemEx.getMessage()));
        logger.error("unknown error,please check program code:"+systemEx.getMessage()+"："+systemEx.toString(),systemEx);
        systemEx.printStackTrace();
        return result;
    }



}